package com.tiancai.service.Impl;

import com.tiancai.constant.MessageConstant;
import com.tiancai.context.BaseContext;
import com.tiancai.exception.AccountNotFoundException;
import com.tiancai.exception.UsernameErrorException;
import com.tiancai.pojo.dto.UserDto;
import com.tiancai.pojo.po.User;
import com.tiancai.mapper.UserMapper;
import com.tiancai.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tiancai
 * @since 2025-03-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(String email, String password){
        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUserEmail(email);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        if (!password.equals(user.getPassword())) {
            throw new UsernameErrorException(MessageConstant.USERNAME_ERROR);
        }
        //3、返回实体对象
        return user;
    }

    /**
     * 更新用户信息
     * @param userDto
     */
    public void updateUser(UserDto userDto) {
        //需要查看userDto里的数据为不为空,
        User user = userMapper.selectById(BaseContext.getCurrentId());

        Optional.ofNullable(userDto.getPhone()).ifPresent(user::setPhone);
        Optional.ofNullable(userDto.getAvatar()).ifPresent(user::setAvatar);
        Optional.ofNullable(userDto.getUsername()).ifPresent(user::setUsername);
        Optional.ofNullable(userDto.getRemark()).ifPresent(user::setRemark);
        Optional.ofNullable(userDto.getPassword()).ifPresent(user::setPassword);


        userMapper.updateById(user);
    }
}
